#from  poset_p2p import *

import wx
import os
import shutil

def Load(self,e,control,desc,ext = None):
	#set_status(self,"load "+desc)
	wildcard = "*.*"
	if ext is not None:
		wildcard = " "+ desc +" files (*."+ext+")|*."+ext+"|any file (*.*)|*.*"
	addtext  = ""
	if desc is not None: addtext  = " ("+str(desc)+")"
	control.dirname = ''
	dlg = wx.FileDialog(self, "Choose a file"+addtext, control.dirname, "", wildcard, wx.OPEN)
	if dlg.ShowModal() == wx.ID_OK:
		control.filename=dlg.GetFilename()
		control.dirname=dlg.GetDirectory()
		f=open(os.path.join(control.dirname,control.filename),'r')
		data = f.read() 
		control.SetValue(data)
		f.close()
	dlg.Destroy()
	#set_status(self,desc+" loaded")

def Save(self,e,control,desc,ext = None):
	#set_status(self,"save "+desc)
	wildcard = "*.*"
	if ext is not None:
		wildcard = " "+ desc +" files (*."+ext+")|*."+ext+"|any file (*.*)|*.*"
	addtext  = ""
	if desc is not None: addtext  = " ("+str(desc)+")"
        dlg = wx.FileDialog(self, "Save"+addtext, control.dirname, control.filename, wildcard, \
                wx.SAVE | wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            # Grab the content to be saved
            itcontains = control.GetValue()
            # Open the file for write, write, close
            control.filename=dlg.GetFilename()
            control.dirname=dlg.GetDirectory()
            filehandle=open(os.path.join(control.dirname, control.filename),'wb')
            filehandle.write(itcontains)
            filehandle.close()
        # Get rid of the dialog to keep things tidy
        dlg.Destroy()
	#set_status(self,desc+" saved")

def SaveFile(self,e,input_file,desc,ext = None):
	dirname,filename = os.path.split(input_file)
	#set_status(self,"save "+desc)
	wildcard = "*.*"
	if ext is not None:
		wildcard = " "+ desc +" files (*."+ext+")|*."+ext+"|any file (*.*)|*.*"
	addtext  = ""
	if desc is not None: addtext  = " ("+str(desc)+")"
        dlg = wx.FileDialog(self, "Save"+addtext, dirname, filename, wildcard, \
	        wx.SAVE | wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            # Open the file for write, write, close
            destfilename=dlg.GetFilename()
            destdirname=dlg.GetDirectory()
            shutil.copy( input_file , destdirname)
            os.rename( os.path.join(destdirname,os.path.split(input_file)[1]) , os.path.join(destdirname,destfilename))
        # Get rid of the dialog to keep things tidy
        dlg.Destroy()
	#set_status(self,desc+" saved")

def show_error(container,message):
	dlg = wx.MessageDialog(container, message, 'Error', wx.OK | wx.ICON_ERROR)
	dlg.ShowModal()
	dlg.Destroy()


